package com.bootdo.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ctc.wstx.util.StringUtil;


public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(s+"\r");
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
    public static void download(String file,Long agentId,HttpServletResponse response) {
    	//高效
        BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	String in = "密钥获取有误，请联系管理员";
    	response.reset();
    	response.addHeader("Content-Disposition", "attachment;filename=" + agentId + "_pub.key");
    	response.addHeader("Content-Length", "" + file.length());
    	response.setContentType("application/octet-stream");
    	in = file;
    	try{
	    	bis = new BufferedInputStream(new ByteArrayInputStream(in.getBytes("utf-8")));
	    	bos = new BufferedOutputStream(response.getOutputStream());
	    	byte[] buff = new byte[in.length()];
	    	@SuppressWarnings("unused")
			int bytesRead = 0;
	    	while(-1 !=(bytesRead = (bis.read(buff,0, buff.length)))){
	    		bos.write(buff, 0, buff.length);
	    	}
    	} catch(Exception e){
    		e.printStackTrace();
    	} finally{
		    	if(bis != null){
		    		try {
						bis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    	}
		    	if(bos != null){
			    	try {
						bos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			    }
		   }
    }
    
    @SuppressWarnings("resource")
	public static String uploadOpenSSL(MultipartFile file) {
		String line = "";
		String result = "";
		try {
			System.out.println(file.getBytes().length);
			BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream())); // 建立一个对象，它把文件内容转成计算机能读懂的语言
			line = br.readLine();
			while (line != null) {
				result = result + line; 
				line = br.readLine(); // 一次读入一行数据
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
    
    /*public static File mulTransferFile(MultipartFile file){
        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 

        File f = fi.getStoreLocation();
        
        return f;
    }*/

}
